﻿using System.IdentityModel.Selectors;
using Ipmce.RemoteVoting.Backend.DataAccess;
using Ipmce.RemoteVoting.Backend.DataAccess.Exceptions;
using Ipmce.RemoteVoting.Backend.VotingService.Utils;
using Ipmce.RemoteVoting.Common.Tools;

namespace Ipmce.RemoteVoting.Backend.VotingService
{
	class UserNameValidator : UserNamePasswordValidator
	{
		private readonly IVoterRepositoryFactory _voterRepositoryFactory;
		private readonly IPasswordCreator _passwordCreator;

		public UserNameValidator(IVoterRepositoryFactory voterRepository, IPasswordCreator passwordCreator)
		{
			_voterRepositoryFactory = voterRepository;
			_passwordCreator = passwordCreator;
		}

		public override void Validate(string userName, string password)
		{
			Voter voter;
			try
			{
				using (var repository = _voterRepositoryFactory.Create())
				{
					voter = repository.GetByPassportNumber(userName);	
				}
			}
			catch (EntityNotFoundException)
			{
				throw new System.IdentityModel.Tokens.SecurityTokenException(
						  "Unknown Username or Password");
			}
			if (string.IsNullOrEmpty(voter.SmsCode))
			{
				throw new System.IdentityModel.Tokens.SecurityTokenException(
					  "Unknown Username or Password");
			}
			if (password != _passwordCreator.CreatePasswordFromHash(voter.SmsCode, voter.Dg2Hash))
			{
				throw new System.IdentityModel.Tokens.SecurityTokenException(
						  "Unknown Username or Password");
			}
		}
	}
}